package com.ovt.doorbell.payment.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ovt.doorbell.payment.dao.vo.PageInfo;
import com.ovt.doorbell.payment.dao.vo.Permission;
import com.ovt.doorbell.payment.dao.vo.PermissionGrant;
import com.ovt.doorbell.payment.dao.vo.UserPermission;
import com.ovt.doorbell.payment.service.context.SessionContext;
import com.ovt.doorbell.payment.service.exception.ServiceException;
import com.ovt.doorbell.payment.service.manager.PermissionManager;
import com.ovt.doorbell.payment.service.manager.UserPermissionManager;

@Service
public class PermissionServiceImpl implements PermissionService
{
    
    @Autowired
    private PermissionManager permissionManager;
    @Autowired
    private UserPermissionManager userPermissionManager;
    @Override
    
    public List<PermissionGrant> getPermissionGrantByUserId(PageInfo page, int userId)
            throws ServiceException
    {
        List<PermissionGrant> permissiongrants = new ArrayList<PermissionGrant>();
        
        List<Permission> permissions1 = permissionManager.getPermissionByUserId(userId);
        List<Permission> permissions2 = permissionManager.getUnPermissionByUserId(userId);
        
        for(int i = 0; i < permissions2.size(); i++){
            PermissionGrant permissiongrant = new PermissionGrant();
            permissiongrant.setPermission(permissions2.get(i));
            permissiongrant.setState("UNGRANT");
            permissiongrants.add(permissiongrant);
        }
        
        for(int i = 0; i < permissions1.size(); i++){
            PermissionGrant permissiongrant = new PermissionGrant();
            permissiongrant.setPermission(permissions1.get(i));
            permissiongrant.setState("UNGRANT");
            permissiongrants.add(permissiongrant);
        }
        
        return permissiongrants;
    }
    
    @Override
    public void grantPermission(int userId, int permId) throws ServiceException
    {
        Timestamp stamp = new Timestamp((new Date()).getTime());
        UserPermission userPermission = new UserPermission();
        userPermission.setUserId(userId);
        userPermission.setPermId(permId);
        userPermission.setCreateTime(stamp);
        userPermission.setUpdateTime(stamp);
        userPermission.setUpdateBy((int) SessionContext.getCurrentUser().getId());
        userPermissionManager.saveUserPermission(userPermission);
    }
    
    @Override
    public void revokePermission(int userId, int permId) throws ServiceException
    {
        userPermissionManager.deleteUserPermission(userId, permId);
    }
    
    @Override
    public List<Permission> getPermissionList(PageInfo page)
            throws ServiceException
    {
        return permissionManager.getAllPermission(page);
    }
    
    
}
